<template>
  <BasicTable @register="registerTable">
    <template #toolbar>
      <a-button type="primary" @click="handleCreate">添加</a-button>
    </template>
    <template #action="{ record }">
      <TableAction
        :actions="[
          {
            label: '编辑',
            icon: 'ant-design:edit-outlined',
            onClick: handleEditDict.bind(null, record),
          },
          {
            label: '字典配置',
            icon: 'ant-design:setting-outlined',
            onClick: handleEditDictItem.bind(null, record),
          },
          {
            label: '删除',
            icon: 'ic:outline-delete-outline',
            onClick: handleDeleteDict.bind(null, record),
          },
        ]"
      />
    </template>
  </BasicTable>
  <DictModal @register="registerModal" @success="reload" />
  <DictItemListDrawer @register="registerDrawer" />
</template>

<script lang="ts" setup>
  import { BasicTable, useTable, BasicColumn, TableAction } from '/@/components/Table';
  import { message, Modal } from 'ant-design-vue';
  import { getDictList } from '/@/api/base';
  import { searchFormSchema, dictColumns } from './dict.data';
  import DictModal from './components/DictModal.vue';
  import DictItemListDrawer from './components/DictItemListDrawer.vue';
  import { useModal } from '/@/components/Modal';
  import { useDrawer } from '/@/components/Drawer';
  import { deleteDictById } from '/@/api/base';

  const [registerTable, { reload, updateTableDataRecord }] = useTable({
    title: '字典列表',
    api: getDictList,
    rowKey: 'id',
    columns: dictColumns,
    showIndexColumn: true,
    tableSetting: {
      cacheKey: 'dict_list',
    },
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    beforeFetch({ pageIndex, pageSize, ...model }) {
      return {
        pageIndex,
        pageSize,
        model,
      };
    },
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  const [registerModal, { openModal }] = useModal();

  const [registerDrawer, { openDrawer }] = useDrawer();

  const handleCreate = () => {
    openModal(true, {
      isUpdate: false,
    });
  };

  const handleEditDict = (record: Recordable) => {
    openModal(true, {
      record,
      isUpdate: true,
    });
  };

  const handleDeleteDict = (record: Recordable) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除所选字典吗?',
      onOk: async () => {
        await deleteDictById(record.id);
        message.success('删除字典信息成功！');
        reload();
      },
    });
  };

  const handleEditDictItem = (record: Recordable) => {
    openDrawer(true, {
      record,
    });
  };
</script>
<style scoped></style>
